<script setup>

import {ref} from "vue";
import axios from "axios";
import {ElLoading, ElMessage} from "element-plus";

const headers = {
  Authorization: localStorage.getItem("auth")
}

//系列下拉框选项(用于新增/修改)
const seriesOptions = [
  {
    value: '1',
    label: '藏选',
  },
  {
    value: '2',
    label: '心悦数字',
  },
  {
    value: '3',
    label: '国漫',
  },
  {
    value: '4',
    label: '鳗鱼',
  },
  {
    value: '5',
    label: '宇宙',
  },
  {
    value: '6',
    label: 'black',
  }
]

//发行方数据
const issuer = [
  {
    value: '1',
    label: '发行方1',
  },
  {
    value: '2',
    label: '发行方2',
  },
  {
    value: '3',
    label: '发行方3',
  },
  {
    value: '4',
    label: '发行方4',
  },
  {
    value: '5',
    label: '发行方5',
  },
  {
    value: '6',
    label: '发行方6',
  },
  {
    value: '7',
    label: '发行方7',
  },
]

//系列下拉框选项（用于搜索）
const seriesOptionsAll = [
  {
    value: '0',
    label: '- 全部 -',
  },
  {
    value: '1',
    label: '藏选',
  },
  {
    value: '2',
    label: '心悦数字',
  },
  {
    value: '3',
    label: '国漫',
  },
  {
    value: '4',
    label: '鳗鱼',
  },
  {
    value: '5',
    label: '宇宙',
  },
  {
    value: '6',
    label: 'black',
  }
]


//搜索的藏品系列值
const goodsSeries = ref("0");
//搜索的藏品名称
const goodsName = ref("");
//搜索的藏品编号
const goodsCode = ref("");
//定义藏表格的引用
const goodsTableRef = ref();
//存储藏品相关数据
const goodsPage = ref({
  records:[]
});
//藏品相关数据加载中
const goodsPageLoading = ref(true);
//当前页码
const goodsPageIndex = ref(1);

//从接口获取商品分页数据
const getGoodsPage = () => {
  goodsPageLoading.value = true;
  axios.post("/api/goods", {
    pageIndex: goodsPageIndex.value,
    pageSize: 8,
    seriesId: parseInt(goodsSeries.value),
    name: goodsName.value,
    code: goodsCode.value
  }, {headers}).then(response => {
    console.log("获取成功");
    goodsPage.value = response.data.value;  //将从接口获取到的数据，赋值给goodsPage对象
    goodsPageLoading.value = false;
  }).catch(error => {
    console.log("获取失败", error.response);
    goodsPageLoading.value = false;
  })
}

getGoodsPage();

//选择的当前藏品
const currentGoods = ref({});

//表示单击行
const handleRowClick = row => {
  if (row != undefined) {
    goodsTableRef.value.data.forEach(r => {
      goodsTableRef.value.toggleRowSelection(r, r.id == row.id);
    })
    currentGoods.value = row;
  }
}
//选择数据key集合
const multipleSelection = ref([]);
const handleSelectionChange = val => {
  multipleSelection.value = val;
  if (multipleSelection.value.length == 1) {
    currentGoods.value = multipleSelection.value[0];
  } else {
    currentGoods.value = {};
  }
}

//控制新增/修改藏品对话框是否显示
const dialogEditGoodsVisible = ref(false);

//新增按钮点击事件
const addGoods = () => {
  console.log("点击新增按钮了..");
  currentGoods.value = {
    id:0,
    mintage: 1,
    circulation: 0
  };
  dialogEditGoodsVisible.value = true;
}

//修改按钮点击事件
const updateGoods = () => {
  dialogEditGoodsVisible.value = true;
}

//商品图片上传之前
const beforeGoodsImageUpload = rawFile => {
  console.log("开始上传了...",rawFile.type);
  if (!rawFile.type.startsWith('image/')) {
    ElMessage.error('请上传图片格式')
    return false;
  } else if (rawFile.size > 1024 * 1024 * 2) {
    ElMessage.error('头像图片不能超过2MB')
    return false;
  }
  return true;
}

//商品图片上传成功后
const handleGoodsImageUploadSuccess = response => {
  console.log("上传成功，图片地址：" + response.value);
  currentGoods.value.image = response.value;
}

//保存按钮加载中
const btnSaveLoading = ref(false);

//藏品保存事件
const saveGoods = () => {
  console.log("点击了保存", currentGoods.value);
  btnSaveLoading.value = true;
  axios.post("/api/goods/save", currentGoods.value, {headers}).then(response => {
    console.log("保存成功");
    btnSaveLoading.value = false;
    dialogEditGoodsVisible.value = false;
    getGoodsPage();
  }).catch(error => {
    console.log("保存失败", error.response);
    btnSaveLoading.value = false;
    ElMessage({
      message: error.response.data.message,
      type: 'warning',
    })
  })
}

//点击是否推荐 Switch
const switchChangeHandler = (val,row,loading) => {
  // console.log("切换了，新值：" + val + "，点的这一行是：" + JSON.stringify(row));
  row[loading] = true;
  axios.post("/api/goods/save", row, {headers}).then(response => {
    console.log("保存成功");
    row[loading] = false;
  }).catch(error => {
    console.log("保存失败", error.response);
    ElMessage({
      message: error.response.data.message,
      type: 'warning',
    })
  })
}

//删除按钮加载中
const btnRemoveLoading = ref(false);

//删除藏品
const removeGoods = () => {
  // console.log("你选中的行有：", multipleSelection.value);
  multipleSelection.value.forEach(goods => {
    btnRemoveLoading.value = true;
    axios.get("/api/goods/remove?id="+goods.id, {headers}).then(response => {
      console.log("删除成功");
      getGoodsPage();
      btnRemoveLoading.value = false;
    }).catch(error => {
      console.log("删除失败", error.response);
      btnRemoveLoading.value = false;
      ElMessage({
        message: error.response.data.message,
        type: 'warning',
      })
    })
  })
}

</script>

<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
    <el-breadcrumb-item>藏品中心</el-breadcrumb-item>
    <el-breadcrumb-item>藏品管理</el-breadcrumb-item>
  </el-breadcrumb>
  <div class="view">
    <div class="vHead">
      <div class="vHLeft">
        系列:
        <el-select v-model="goodsSeries" placeholder="请选择" style="width:140px">
          <el-option
              v-for="item in seriesOptionsAll"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>&nbsp;&nbsp;
        <el-input v-model="goodsName" placeholder="藏品名称" style="width:160px"/>&nbsp;&nbsp;
        <el-input v-model="goodsCode" placeholder="藏品编号" style="width:120px"/>&nbsp;&nbsp;
        <el-button type="primary" @click="getGoodsPage">搜索</el-button>
      </div>
      <div>
        <el-button type="primary" @click="addGoods">新增</el-button>
        <el-button type="default" @click="updateGoods" :disabled="multipleSelection.length != 1">修改</el-button>
        <el-popconfirm title="确认删除吗？"
                       confirm-button-text="是"
                       cancel-button-text="否"
                       @confirm="removeGoods">
            <template #reference>
              <el-button type="warning" :disabled="multipleSelection.length == 0" :loading="btnRemoveLoading">删除</el-button>
            </template>
        </el-popconfirm>
      </div>
    </div>
    <div>
      <el-table :data="goodsPage.records"
                v-loading="goodsPageLoading"
                row-key="id"
                ref="goodsTableRef"
                @current-change="handleRowClick"
                @selection-change="handleSelectionChange"
                stripe
                highlight-current-row
                empty-text="暂无数据"
                style="width: 100%">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="藏品ID" width="80"/>
        <el-table-column label="图片" width="80">
          <template #default="scope">
            <img :src="scope.row.image" width="35" height="30"/>
          </template>
        </el-table-column>
        <el-table-column prop="seriesId" label="系列ID"/>
        <el-table-column prop="name" label="藏品名称" width="200"/>
        <el-table-column prop="mintage" label="铸造量"/>
        <el-table-column prop="circulation" label="流通量"/>
        <el-table-column prop="price" label="发售价"/>
        <el-table-column prop="code" label="编号"/>
        <el-table-column label="是否推荐">
          <template #default="scope">
            <el-switch v-model="scope.row.recommend" :loading="scope.row.recommendLoading" @change="switchChangeHandler(val,scope.row,'recommendLoading')"/>
          </template>
        </el-table-column>
        <el-table-column label="是否新品">
          <template #default="scope">
            <el-switch v-model="scope.row.news" :loading="scope.row.newsLoading" @change="switchChangeHandler(val,scope.row,'newsLoading')"/>
          </template>
        </el-table-column>
        <el-table-column label="是否激活">
          <template #default="scope">
            <el-switch v-model="scope.row.active" :loading="scope.row.activeLoading" @change="switchChangeHandler(val,scope.row,'activeLoading')"/>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next"
                     :default-page-size="goodsPage.pageSize"
                     :total="goodsPage.total"
                     v-model:current-page="goodsPageIndex"
                     @current-change="getGoodsPage"/>
    </div>
  </div>

  <el-dialog
      v-model="dialogEditGoodsVisible"
      :title="(currentGoods.id == 0 ? '新增' : '修改') + '藏品'"
      width="1100" align-center>
    <table width="100%" height="400">
      <tr>
        <td>藏品名称:</td>
        <td>
          <el-input v-model="currentGoods.name" style="width:180px"/>
        </td>
        <td>铸造量:</td>
        <td>
          <el-input-number v-model="currentGoods.mintage" min="1" style="width:180px"/>
        </td>
        <td>流通量:</td>
        <td>
          <el-input-number v-model="currentGoods.circulation" min="0" style="width:180px"/>
        </td>
        <td>发售价:</td>
        <td>
          <el-input-number v-model="currentGoods.price" min="0" precision="2" style="width:180px"/>
        </td>
      </tr>
      <tr>
        <td>发行方:</td>
        <td>
          <el-select v-model="currentGoods.issuerId" style="width:180px" placeholder="请选择发行方">
            <el-option
                v-for="item in issuer"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>&nbsp;&nbsp;
        </td>
        <td>藏品系列:</td>
        <td>
          <el-select v-model="currentGoods.seriesId" style="width:180px" placeholder="请选择藏品系列">
            <el-option
                v-for="item in seriesOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>&nbsp;&nbsp;
        </td>
        <td>区块链信息:</td>
        <td colspan="3">
          <el-input v-model="currentGoods.blockchain" style="width:400px"/>
        </td>
      </tr>
      <tr>
        <td>藏品编号:</td>
        <td>
          <el-input v-model="currentGoods.code" style="width:180px"/>
        </td>
        <td>交易哈希:</td>
        <td>
          <el-input v-model="currentGoods.hash" style="width:180px"/>
        </td>
        <td>发售日期:</td>
        <td>
          <el-date-picker
              v-model="currentGoods.releaseDate"
              style="width:180px"
              type="date"
              placeholder="选择一个日期"
          />
        </td>
        <td>手续费率:</td>
        <td>
          <el-input v-model="currentGoods.feeRate" style="width:180px"/>
        </td>
      </tr>
      <tr>
        <td>是否推荐:</td>
        <td>
          <el-switch v-model="currentGoods.recommend"/>
        </td>
        <td>是否新品:</td>
        <td>
          <el-switch v-model="currentGoods.news"/>
        </td>
        <td>是否激活:</td>
        <td>
          <el-switch v-model="currentGoods.active"/>
        </td>
        <td>
        </td>
        <td>
        </td>
      </tr>
      <tr>
        <td>藏品图片</td>
        <td colspan="7">
          <el-upload
              class="avatar-uploader"
              action="/api/file/uploadImage"
              name="partFile"
              :headers="headers"
              :show-file-list="false"
              :before-upload="beforeGoodsImageUpload"
              :on-success="handleGoodsImageUploadSuccess"
          >
            <img v-if="currentGoods.image" :src="currentGoods.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </td>
      </tr>
    </table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogEditGoodsVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGoods" :loading="btnSaveLoading">保存</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped>

.avatar-uploader .avatar {
  width: 178px;
  height: 148px;
  display: block;
}

</style>